<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :destroy-on-close="true"
    @ok="handleSubmit"
    width="800px"
    ok-text="保存"
  >
    <BasicForm @register="registerForm">
      <template #columnsSlot>
        <div class="flex justify-around w-full mb-10px">
          <div class="w-1/5">Key</div>
          <div class="w-1/5">标签</div>
        </div>
        <div
          v-for="(item, index) in columnsList"
          :key="index"
          class="flex justify-around w-full mt-10px mb-10px"
        >
          <Select
            v-model:value="item.select"
            class="w-2/5"
            mode="tags"
            :options="columnsOption"
            @change="selectChange($event, index)"
          ></Select>
          <Input
            class="w-2/5"
            type="text"
            v-model:value="columnsKeyValue[item.select[0]]"
            placeholder="Basic usage"
          />
          <div class="flex justify-around w-1/5 items-center">
            <!-- <Icon
              icon="ant-design:setting-filled"
              size="20"
              color="#0960BD"
              @click="settingColumnsClick(index)"
            /> -->
            <Icon
              icon="ant-design:delete-filled"
              size="20"
              color="#0960BD"
              @click="deleteColumnsClick(index)"
            />
          </div>
        </div>
        <Button type="primary" @click="addColumnsClick">添加表头</Button>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { Select, Input, Button, message } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormProps, FormSchema } from '/@/components/Form';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    seriesFormList,
    FormItem,
    seriesFormSchema,
    baseFormConfig,
  } from './alarmTableModal.data';
  import { nextTick, ref } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { buildUUID } from '/@/utils/uuid';
  import { getDeviceInfo } from '/@/api/thingsborad/entity/entity';
  import { getAlarmTypeList, getTrustedList } from '/@/api/thingsborad/alarm';

  const emits = defineEmits(['success']);

  //表头列表
  let columnsList = ref<Array<any>>([
    {
      select: 'createdTime',
      input: '创建时间',
    },
  ]);

  // 表头keyValue
  let columnsKeyValue = ref<any>({
    createdTime: '创建时间',
    startTime: '开始时间',
    endTime: '结束时间',
    ackTime: '确认时间',
    clearTime: '清除时间',
    assignTime: '分配时间',
    originatorLabel: '发起者标签',
    originatorType: '发起者类型',
    type: '类型',
    severity: '严重程度',
    status: '状态',
    assignee: '受托人',
  });

  //表头可选项
  let columnsOption = ref<Array<any>>([
    {
      label: 'createdTime',
      value: '创建时间',
    },
    {
      label: 'startTime',
      value: '开始时间',
    },
    {
      label: 'endTime',
      value: '结束时间',
    },
    {
      label: 'ackTime',
      value: '确认时间',
    },
    {
      label: 'clearTime',
      value: '清除时间',
    },
    {
      label: 'assignTime',
      value: '分配时间',
    },
    {
      label: 'originator',
      value: '发起者',
    },
    {
      label: 'originatorLabel',
      value: '发起者标签',
    },
    {
      label: 'originatorType',
      value: '发起者类型',
    },
    {
      label: 'type',
      value: '类型',
    },
    {
      label: 'severity',
      value: '严重程度',
    },
    {
      label: 'status',
      value: '状态',
    },
    {
      label: 'assignee',
      value: '受托人',
    },
  ]);

  const seriesList = ref<Array<FormItem>>(cloneDeep(seriesFormList));
  const flag = ref<boolean>(true);
  const entityName = ref<string>('');

  let schemas: FormSchema[] = [
    {
      field: 'Divider4',
      label: '名称',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'tableTitle',
      component: 'Input',
      label: '表格标题名称',
      required: true,
      componentProps: {
        placeholder: '请输入表格名称',
      },
    },
    {
      field: 'Divider3',
      label: '表头',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'columns',
      label: '',
      component: 'Input',
      slot: 'columnsSlot',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'Divider1',
      label: '告警源',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'alarmType',
      component: 'Select',
      label: '告警源 类型',
      required: true,
      defaultValue: '函数',
      componentProps: {
        options: [
          {
            label: '函数',
            value: '函数',
          },
        ],
      },
    },
    {
      field: 'alarmFlag',
      component: 'Input',
      label: '告警源 标签',
      required: true,
      componentProps: {
        placeholder: '请输入标签',
      },
    },
    {
      field: 'Divider2',
      label: '筛选器',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'alarmTypeList',
      component: 'CheckboxGroup',
      label: '告警状态列表',
      componentProps: {
        options: [
          {
            label: '激活',
            value: '激活',
          },
          {
            label: '已清除',
            value: '已清除',
          },
          {
            label: '已确认',
            value: '已确认',
          },
          {
            label: '未确认',
            value: '未确认',
          },
        ],
      },
    },
    {
      field: 'deepAlarmTypeList',
      component: 'CheckboxGroup',
      label: '告警状态列表',
      componentProps: {
        options: [
          {
            label: '危险',
            value: '危险',
          },
          {
            label: '重要',
            value: '重要',
          },
          {
            label: '次要',
            value: '次要',
          },
          {
            label: '警告',
            value: '警告',
          },
          {
            label: '不确定',
            value: '不确定',
          },
        ],
      },
    },
    {
      field: 'alarmClassifyList',
      component: 'Select',
      label: '告警类型列表',
      required: true,
      componentProps: {},
    },
    {
      field: 'Trustee',
      component: 'Select',
      label: '受托人',
      required: true,
      componentProps: {},
    },
    {
      field: 'deepAlarmTypeList',
      component: 'CheckboxGroup',
      label: '',
      componentProps: {
        options: [
          {
            label: '检索已传递的警报',
            value: '检索已传递的警报',
          },
        ],
      },
    },
    {
      field: 'Divider5',
      label: '表格功能按钮',
      component: 'Divider',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'buttonFunction',
      component: 'CheckboxGroup',
      label: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '显示告警活动',
            value: '显示告警活动',
          },
          {
            label: '显示告警详细信息',
            value: '显示告警详细信息',
          },
          {
            label: '允许分配告警',
            value: '允许分配告警',
          },
          {
            label: '允许确认告警',
            value: '允许确认告警',
          },
          {
            label: '允许清除告敬',
            value: '允许清除告敬',
          },
        ],
      },
    },
  ];

  const [registerForm, { validate, setFieldsValue, updateSchema }] = useForm({
    layout: 'vertical',
    schemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(
    async (formData: Recordable) => {
      setModalProps({
        ...modalStyleSetting,
      });

      // 获取 告警类型列表
      let params: any = {
        pageSize: 25,
        page: 0,
      };
      //数据清洗赋值
      let alarmType = await getAlarmTypeList(params);
      let dataList: Array<any> = [];
      alarmType.data.forEach((item) => {
        dataList.push({
          label: item.type,
          value: item.tenantId.id,
        });
      });
      updateSchema({
        field: 'alarmClassifyList',
        componentProps: {
          mode: 'multiple',
          listHeight: '100',
          options: dataList,
        },
      });

      //获取受托人
      params = {
        pageSize: 50,
        page: 0,
        sortProperty: 'email',
        sortOrder: 'ASC',
      };

      let trustedList = await getTrustedList(params);
      dataList = [];
      trustedList.data.forEach((item) => {
        dataList.push({
          label: `姓名：${item.firstName} 邮箱：${item.email}`,
          value: item.id.id,
        });
      });
      updateSchema({
        field: 'Trustee',
        componentProps: {
          listHeight: '100',
          options: dataList,
        },
      });

      await setFieldsValue({
        ...formData,
      });
      if (formData.series) {
        seriesList.value = Array.from({ length: formData.series.length }, () => ({
          key: buildUUID(),
          Form: useForm(Object.assign({ schemas: seriesFormSchema }, baseFormConfig) as FormProps),
        }));
        seriesList.value.forEach((item, index) => {
          nextTick(() => {
            item.Form[1].setFieldsValue({ ...formData.series[index] });
          });
        });
      }
      // 设备名称暂时没用到
      entityName.value = (await getDeviceInfo(JSON.parse(formData.deviceId).id)).name;
    },
  );

  //编辑表头
  function settingColumnsClick(index: number) {
    
  }

  //删除表头
  function deleteColumnsClick(index: number) {
    columnsList.value.splice(index, 1);
  }

  //添加表头
  function addColumnsClick() {
    columnsList.value.push({
      select: '',
      input: '',
    });
  }

  //
  function selectChange(value, index) {
    
    

    if (value.length > 1) {
      message.warning('只能设置一个字段，请删除后再选择或创建');
      return;
    }
    
  }

  // 添加series项
  const handleAdd = () => {
    seriesList.value.push({
      key: buildUUID(),
      Form: useForm(
        Object.assign(
          { schemas: seriesFormSchema },
          {
            ...baseFormConfig,
            labelCol: {
              style: {
                marginTop: '20px',
              },
            },
          },
        ) as FormProps,
      ),
    });
  };
  // 删除series项
  const handleDelete = (key: string) => {
    seriesList.value = seriesList.value.filter((item) => item.key !== key);
  };

  const handleSubmit = async () => {
    flag.value = !flag.value;
    let values = {};
    let series: Array<any> = [];
    const value = await validate();
    Object.assign(values, value);
    for (const item in seriesList.value) {
      const { validate } = seriesList.value[item].Form[1];
      const value = await validate();
      series.push(value);
    }
    Object.assign(values, { series });
    emits('success', values);
    closeModal();
  };
</script>
